import api from '@/api/socket';

const state = {
    userName: null,
    key: null
};

const getters = {
    userName: state => state.userName,
    userKey: state => state.key,
};

const mutations = {
    setUserName(state, { userName }) {
        state.userName = userName;
    },
    setKey(state, { key }) {
        state.key = key;
    }
};

const actions = {
    //初始化连接
    getConnection(context) {
        return new Promise((resolve, reject) => {
            api.connect(rst => {
                if (rst.code) {
                    context.commit('setKey', rst.data);
                    resolve(rst);
                } else {
                    // alert('连接失败,' + rst.msg);
                    reject(rst);
                }
            });
        });
    },
    //设置登录人名称
    setUserName(context, data) {
        context.commit('setUserName', { userName: data.userName });
        return;
        return new Promise((resolve, reject) => {
            var userName = data.userName;
            var uPattern = /^.{1,8}$/
            if (uPattern.test(userName)) {
                api.login(userName, rst => {
                    if (rst.code) {
                        context.commit('setUserName', { userName });
                    }
                    resolve(rst);
                });
            } else {
                Utils.alert('登录人名称不合法:1位-8位');
                reject('登录人名称不合法:1位-8位');
            }
        });

    },
    login(context, data) {
        console.log('用户登录');
        return new Promise((resolve, reject) => {
            var userName = data.userName;
            var uPattern = /^.{1,8}$/
            if (uPattern.test(userName)) {
                api.login(userName, rst => {
                    if (rst.code)
                        context.commit('setUserName', { userName });
                    resolve(rst);
                });
            } else {
                reject('登录人名称不合法:1位-8位');
            }
        });
    },
    logOut(context) {
        console.log('用户登出 action');
        return new Promise((resolve, reject) => {
            api.logOut(rst => {
                context.commit('setUserName', { userName: null });
                resolve(rst);
            });
        });

    }
};

export default {
    state,
    getters,
    actions,
    mutations
}